package com.zs.lib_base.utils

import android.annotation.SuppressLint
import android.content.Context
import android.view.Gravity
import android.widget.Toast
import com.zs.lib_base.ext.d
import com.zs.lib_base.ext.e

private lateinit var toast: Toast

fun showToast(msg: String, duration: Int = Toast.LENGTH_SHORT) {
    try {
        if (!::toast.isInitialized) {
            "Toast暂未初始化".d()
            return
        }
            toast.apply {
                setDuration(duration)
                setText(msg)
                show()
            }
    } catch (e: Exception) {
        "showToast 发生了异常：${e.message}".e()
        e.printStackTrace()
    }
}

object ToastUtil {

    /**
     * 使用applicationContext为了避免内存泄露
     */
    @SuppressLint("ShowToast")
    fun init(context: Context) {
        try {
            toast = Toast.makeText(context.applicationContext, "", Toast.LENGTH_LONG).apply {
                setGravity(Gravity.CENTER, 0, 0)
            }
        } catch (e: Exception) {
            "ToastUtil 初始化发生了异常：${e.message}".e()
            e.printStackTrace()
        }
    }
}